//
//  SeekoArticleTableViewController.m
//  MokoAPP
//
//  Created by 현식 강 on 11. 8. 2..
//  Copyright 2011 아이온. All rights reserved.
//

#import "SeekoArticleTableViewController.h"
#import "MokoAppDelegate.h"
#import "HTMLParser.h"
#import "SeekoArticleContentWebView.h"
#import "SeekoBoardListTableViewController.h"
#import "ScrollingLabel.h"
#import "MemoWriteViewController.h"
#import "ParsingDirector.h"
#import "ArticleAndCommentVO.h"
#import "SeekoBoardListTableViewController.h"
#import "CommentVO.h"
#import "UIImageCategory.h"

@implementation SeekoArticleTableViewController
@synthesize link, username, articleDate;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil link:(NSString*)_link username:(NSString*)_username articleDate:(NSString*)date isNoticeArticle:(BOOL)noticeArticle {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if( self ) {
        //articleVOs = [[NSMutableArray alloc] init];
        self.articleDate = date;
        self.username = _username;
        GET_APPDELEGATE;
        link = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%@/zboard4/%@", delegate.configVO.siteHostAddress,_link]];
        
        // 백버튼 커스터마이징
        // backBarButtonItem 이었나 암튼 이거로는 커스텀뷰가 안돼서 이렇게 지정
        UIImage* image = [UIImage imageNamed:@"back_left_button.png"];
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:image forState:UIControlStateNormal];
        [button addTarget:self.navigationController action:@selector(backStep) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, 0, image.size.width/2, image.size.height/2);
        UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:button];
        self.navigationItem.hidesBackButton = YES;
        self.navigationItem.leftBarButtonItem = item;
        [item release];
        // 새로고침 버튼 우측에 붙이기
        image = [UIImage imageNamed:@"refresh_on.png"];
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:image forState:UIControlStateNormal];
        [button addTarget:self action:@selector(reloadAllData) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, 0, 25, 25);
        item = [[UIBarButtonItem alloc] initWithCustomView:button];
        self.navigationItem.rightBarButtonItem = item;
        [item release];
        
        // 커스텀 타이틀 네비게이션 바 붙이기
        ScrollingLabel* label = [[ScrollingLabel alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont boldSystemFontOfSize:15];
        UIView* titleView = [[UIView alloc] initWithFrame:CGRectZero];
        titleView.clipsToBounds = YES;
        [titleView addSubview:label];
        self.navigationItem.titleView = titleView;
        
        
        [titleView sizeToFit];
        [titleView release];
        label.backgroundColor = [UIColor clearColor];
        [label release];
        if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
            contentViewController = [[SeekoArticleViewController alloc] initWithNibName:@"SeekoArticleViewController" bundle:[NSBundle mainBundle] link:self.link parentController:self];
        else
            contentViewController = [[SeekoArticleViewController alloc] initWithNibName:@"SeekoArticleViewController-iPad" bundle:[NSBundle mainBundle] link:self.link parentController:self];

        contentViewController.isNoticeArticle = noticeArticle;
                
        contentViewController.articleDate = date;
    }
    return self;
}
-(void)reloadAllData {
    GET_APPDELEGATE;
    [delegate.httpClient requestURL:link httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
}
-(void)finishLoading:(NSData *)data {
    ParsingDirector* director = [ParsingDirector sharedParsingDirector];
    director.responseData = data;
    vo = [director getArticleAndComment];
    articleVOs = [vo.commentArr retain];
    if( [vo.title length] > 0 ) {
        contentViewController.articleLinks = vo.articleLinks;
        contentViewController.articleImages = vo.articleImgs;
        contentViewController.articleDate = articleDate;
        contentViewController.articleContent = vo.viewRawContent;
        contentViewController.articleTitle = vo.title;

        if( vo.editable == YES ) {
            contentViewController.modifyButton.hidden = NO;
        }
        if( vo.deletable == YES ) {
            contentViewController.deleteButton.hidden = NO;
        }
        
        CGRect titleframe = [self.navigationItem.titleView frame];
        CGSize labelSize = [vo.title sizeWithFont:[UIFont boldSystemFontOfSize:13] constrainedToSize:titleframe.size];
        titleframe.size = labelSize;
        self.navigationItem.titleView.frame = titleframe;
        ScrollingLabel* titleLabel = (ScrollingLabel*)[[self.navigationItem.titleView subviews] objectAtIndex:0];
        [titleLabel setText:vo.title];
        titleLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
        [titleLabel sizeToFit];
        CGRect frame = titleLabel.frame;
        frame.size.width = [[UIScreen mainScreen] bounds].size.width - 80;
        self.navigationItem.titleView.frame = frame;
        float labelX = (self.navigationItem.titleView.frame.size.width - titleLabel.frame.size.width) / 2;
        frame = titleLabel.frame;
        frame.origin.x = labelX;
        titleLabel.frame = frame;
        if( titleLabel.frame.size.width > self.navigationItem.titleView.frame.size.width )
            [titleLabel startScrolling];

        // 유저이름
        contentViewController.userNameLabel.text = [username stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        contentViewController.articleDate = self.articleDate;
        if( [vo.userLevelStr length] > 0 ) {
            NSString* u_level = vo.userLevelStr;
            contentViewController.userLevelLabel.text = u_level;
            contentViewController.userLevelLabel.textColor = [UIColor redColor];
        }
        contentViewController.userId = vo.userId;

        [self.tableView reloadData];
        // 키보드 감추기
        NSArray* subviews = [self.view subviews];
        for( UIView* views in subviews ) 
            [views resignFirstResponder];
        
        [contentViewController.contentWebView loadHTMLString:vo.viewRawContent images:vo.articleImgs links:vo.articleLinks baseURL:nil ];
        
    } else {
        UIAlertView* av = [[UIAlertView alloc] initWithTitle:@"에러" message:@"해당 글은 현재 볼수 없거나 삭제 된 글입니다." delegate:self cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        av.tag = 200;
        [av show];
        [av release];
    }
    for( UIViewController* controller in [self.navigationController viewControllers] ) {
        if( [controller isKindOfClass:NSClassFromString(@"SeekoBoardListTableViewController")] == YES ) {
            if( [[((SeekoBoardListTableViewController*)controller).searchVO.dic objectForKey:@"id"] isEqualToString:@"sponsor"] == NO )
                [controller performSelector:@selector(finishLoading:) withObject:data];
            break;
        }
    }
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [articleDate release];
    contentViewController = nil;
    [articleVOs release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.separatorColor = RGB(211, 211, 211);
    self.tableView.tableHeaderView = contentViewController.view;
    self.tableView.backgroundColor = [UIColor clearColor];
    GET_APPDELEGATE;
    self.tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    [delegate.httpClient requestURL:link httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [articleVOs count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentVO* cvo = [articleVOs objectAtIndex:indexPath.row];
    
    NSString* cellText = cvo.content;
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:15.0];
    CGSize constraintSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
        return labelSize.height + 40;
    }
    else return labelSize.height + 25;
}
-(void)commentLongPress:(id)sender {
    
    UILongPressGestureRecognizer* gr = (UILongPressGestureRecognizer*)sender;
    if ([gr state] == UIGestureRecognizerStateBegan) {
        UIView* view = [gr view];
        selectedIndex = view.tag;
        UIActionSheet* sheet = [[UIActionSheet alloc] init];
        sheet.delegate = self;
        if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
            sheet.cancelButtonIndex = 0;
            [sheet addButtonWithTitle:@"취소"];
        }
        sheet.title = [NSString stringWithFormat:@"선택된 회원 %@ 님", ((CommentVO*)[articleVOs objectAtIndex:selectedIndex]).name]; 
        [sheet addButtonWithTitle:@"댓글 복사"];
        [sheet addButtonWithTitle:@"회원 정보"];
        GET_APPDELEGATE;
        if( delegate.httpClient.isLogin == YES ) 
            [sheet addButtonWithTitle:@"쪽지 보내기"];
        [sheet addButtonWithTitle:@"이름으로 검색"];
        sheet.tag = 10;
        [sheet showFromTabBar:self.tabBarController.tabBar];
        [sheet release];
    }
}
-(void)memberInfo:(NSData*)data {
    ParsingDirector* director = [ParsingDirector sharedParsingDirector];
    director.responseData = data;
    [director memberInfo];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 댓글 액션 시트
    if( actionSheet.tag == 10 ) {
        CommentVO* cvo = [articleVOs objectAtIndex:selectedIndex];
        NSString* userId = cvo.commentID;
        NSString* userName = cvo.name;
        // 댓글 복사
        if( buttonIndex == actionSheet.cancelButtonIndex + 1 ) {
            [UIPasteboard generalPasteboard].string = cvo.content;
            
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"복사 완료" message:@"글 내용이 복사 되었습니다." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
            [alert show];
            [alert release];
        }
        // 회원 정보
        else if(buttonIndex == actionSheet.cancelButtonIndex + 2) {
            GET_APPDELEGATE;
            NSString* addr = [NSString stringWithFormat:@"%@/zboard4/view_info2.php?member_no=%@", delegate.configVO.siteHostAddress, userId];
            
            [delegate.httpClient requestURL:addr httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:self selector:@selector(memberInfo:)];
        }
        // 이름으로 검색
        else if( actionSheet.numberOfButtons-1 == buttonIndex ) {
            NSArray* controllers = self.navigationController.viewControllers;
            SeekoBoardListTableViewController* list = [controllers objectAtIndex:[controllers count]-2];
            [list.searchDisplayController setActive:YES];
            [list searchDisplayController:nil shouldReloadTableForSearchScope:0];
            list.searchDisplayController.searchBar.text = userName;
            [list searchBarSearchButtonClicked:list.searchDisplayController.searchBar];
            [self.navigationController popViewControllerAnimated:YES];
        }  
        // 쪽지 보내기
        else if( buttonIndex != 0 && buttonIndex != -1 ) {
            MemoWriteViewController* memoViewController;
            if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
                memoViewController = [[MemoWriteViewController alloc] initWithNibName:@"MemoWriteViewController" bundle:nil];
            else
                memoViewController = [[MemoWriteViewController alloc] initWithNibName:@"MemoWriteViewController-iPad" bundle:nil];
            memoViewController.toUserId = userId;
            memoViewController.toUserName = userName;
            memoViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self presentModalViewController:memoViewController animated:YES];
            [memoViewController release];
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
        UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:14.0];
        UIImage* commentImage = [UIImage imageNamed:@"comment_left.png"];
        commentImage = [commentImage ResizedImage:CGRectMake(0, 0, commentImage.size.width * 0.75, commentImage.size.height * 0.75)];
        cell.imageView.image = commentImage;
        cell.textLabel.font = cellFont;
        cell.textLabel.numberOfLines = 0;
        UILongPressGestureRecognizer *longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(commentLongPress:)];
        [cell addGestureRecognizer:longPressGr];
        [longPressGr release];
    }
    cell.tag = indexPath.row;

    if( (indexPath.row & 1) == 1 ) {
        cell.contentView.backgroundColor = RGB(237, 237, 237);
        cell.textLabel.backgroundColor = cell.contentView.backgroundColor;
        cell.detailTextLabel.backgroundColor = cell.contentView.backgroundColor;
    }
    else {
        cell.contentView.backgroundColor = RGBA(247, 247, 247, 1.0);
        cell.textLabel.backgroundColor = cell.contentView.backgroundColor;
        cell.detailTextLabel.backgroundColor = cell.contentView.backgroundColor;
    }
    CommentVO* cvo = [articleVOs objectAtIndex:indexPath.row];
    
    cell.textLabel.text = cvo.content;
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    NSString* level = cvo.level;
    if( [level length] == 6 )
        cell.detailTextLabel.textColor = [UIColor redColor];
    else
        cell.detailTextLabel.textColor = [UIColor grayColor];
    [cell.textLabel sizeToFit];
    [cell.contentView sizeToFit];
    NSString* name = cvo.name;
    NSString* date = cvo.date;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ / %@", name, date];
    // Configure the cell...

    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate
-(void)commentDeleteFinished:data {
    NSString* str = [[NSString alloc] initWithData:data encoding:EUC_KR];
    if( [str indexOf:@"\"refresh\""] == -1 ) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"에러 발생" message:@"댓글을 지우는 도중 에러가 발생하였습니다." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [alert show];
        [alert release];
    } else {
        [self reloadAllData];
    }
    [str release];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if( alertView.tag == 100 && buttonIndex == 1) {
        GET_APPDELEGATE;
        CommentVO* cvo = [articleVOs objectAtIndex:selectedIndex];
        NSString* c_no = cvo.deletableCommentID;
        
        assert(c_no != nil );
        
        NSString* param = [NSString stringWithFormat:@"c_no=%@&id=%@", c_no, contentViewController.boardId];
        
        [delegate.httpClient requestURL:[NSString stringWithFormat:@"%@/zboard4/del_comment_ok.php", delegate.configVO.siteHostAddress] httpMethod:@"POST" bodyData:[param dataUsingEncoding:EUC_KR] isMultiPart:NO boundary:nil target:self selector:@selector(commentDeleteFinished:)];
    }
    else if( alertView.tag == 200 && buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentVO* cvo = [articleVOs objectAtIndex:indexPath.row];
    NSString* name = cvo.name;
    NSString* deleteCommentId = cvo.deletableCommentID;
    // 지우기 가능한 댓글일때(장터는 댓글 삭제 불가)
    if( [deleteCommentId length] > 0 ) {
        if( [contentViewController.boardId isEqualToString:@"buysell"] == NO ) {
            selectedIndex = indexPath.row;
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"댓글 삭제" message:@"댓글을 삭제 하시겠습니까?" delegate:self cancelButtonTitle:@"취소" otherButtonTitles:@"확인", nil];
            alert.tag = 100;
            [alert show];
            [alert release];
        }
    } else {
        if( [contentViewController canWriteComment] ) {
            contentViewController.commentContentTextView.text = [NSString stringWithFormat:@"%@ %@님 // ", contentViewController.commentContentTextView.text, name];
            // placeholder 제거를 위해 호출
            [contentViewController.commentContentTextView textChanged:nil];
            // 포커스 이동
            [self.tableView setContentOffset:CGPointMake(0, contentViewController.commentContentTextView.frame.origin.y) animated:NO];
            GET_APPDELEGATE;
            if( delegate.httpClient.isLogin == YES ) {
                // 로그인까지 했으면 키보드창 뜨게
                [contentViewController.commentContentTextView becomeFirstResponder];
            }
        }
    }
}

@end
